<?php


/**
 * 获得查询时间和次数，并赋值给smarty
 *
 * @access  public
 * @return  void
 */
function assign_query_info()
{
	if ($GLOBALS['db']->queryTime == '')
	{
		$query_time = 0;
	}
	else
	{
		if (PHP_VERSION >= '5.0.0')
		{
			$query_time = number_format(microtime(true) - $GLOBALS['db']->queryTime, 6);
		}
		else
		{
			list($now_usec, $now_sec)     = explode(' ', microtime());
			list($start_usec, $start_sec) = explode(' ', $GLOBALS['db']->queryTime);
			$query_time = number_format(($now_sec - $start_sec) + ($now_usec - $start_usec), 6);
		}
	}
	$GLOBALS['smarty']->assign('query_info', sprintf($GLOBALS['_LANG']['query_info'], $GLOBALS['db']->queryCount, $query_time));

	/* 内存占用情况 */
	if ($GLOBALS['_LANG']['memory_info'] && function_exists('memory_get_usage'))
	{
		$GLOBALS['smarty']->assign('memory_info', sprintf($GLOBALS['_LANG']['memory_info'], memory_get_usage() / 1048576));
	}

	/* 是否启用了 gzip */
	$gzip_enabled = gzip_enabled() ? $GLOBALS['_LANG']['gzip_enabled'] : $GLOBALS['_LANG']['gzip_disabled'];
	$GLOBALS['smarty']->assign('gzip_enabled', $gzip_enabled);
}


/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @return  mix
 */
function article_cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0)
{
	static $res = NULL;

	if ($res === NULL)
	{
		$data = read_static_cache('art_cat_pid_releate');
		if ($data === false)
		{
			$sql = "SELECT c.*, COUNT(s.cat_id) AS has_children, COUNT(a.article_id) AS aricle_num ".
               ' FROM ' . TABLEPRE . "article_cat AS c".
               " LEFT JOIN " . TABLEPRE . "article_cat AS s ON s.parent_id=c.cat_id".
               " LEFT JOIN " . TABLEPRE . "article AS a ON a.cat_id=c.cat_id".
               " GROUP BY c.cat_id ".
               " ORDER BY parent_id, sort_order ASC";
			$res = $GLOBALS['db']->getAll($sql);
			write_static_cache('art_cat_pid_releate', $res);
		}
		else
		{
			$res = $data;
		}
	}

	if (empty($res) == true)
	{
		return $re_type ? '' : array();
	}

	$options = article_cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

	/* 截取到指定的缩减级别 */
	if ($level > 0)
	{
		if ($cat_id == 0)
		{
			$end_level = $level;
		}
		else
		{
			$first_item = reset($options); // 获取第一个元素
			$end_level  = $first_item['level'] + $level;
		}

		/* 保留level小于end_level的部分 */
		foreach ($options AS $key => $val)
		{
			if ($val['level'] >= $end_level)
			{
				unset($options[$key]);
			}
		}
	}

	$pre_key = 0;
	foreach ($options AS $key => $value)
	{
		$options[$key]['has_children'] = 1;
		if ($pre_key > 0)
		{
			if ($options[$pre_key]['cat_id'] == $options[$key]['parent_id'])
			{
				$options[$pre_key]['has_children'] = 1;
			}
		}
		$pre_key = $key;
	}

	if ($re_type == true)
	{
		$select = '';
		foreach ($options AS $var)
		{
			$select .= '<option value="' . $var['cat_id'] . '" ';
			$select .= ' cat_type="' . $var['cat_type'] . '" ';
			$select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
			$select .= '>';
			if ($var['level'] > 0)
			{
				$select .= str_repeat('&nbsp;', $var['level'] * 4);
			}
			$select .= htmlspecialchars(addslashes($var['cat_name'])) . '</option>';
		}

		return $select;
	}
	else
	{
		foreach ($options AS $key => $value)
		{
			//$options[$key]['url'] = build_uri('article_cat', array('acid' => $value['cat_id']), $value['cat_name']);
			$options[$key]['url'] = 'article_cat.php?acid='.$value['cat_id'];
		}
		return $options;
	}
}

/**
 * 过滤和排序所有文章分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function article_cat_options($spec_cat_id, $arr)
{
	static $cat_options = array();

	if (isset($cat_options[$spec_cat_id]))
	{
		return $cat_options[$spec_cat_id];
	}

	if (!isset($cat_options[0]))
	{
		$level = $last_cat_id = 0;
		$options = $cat_id_array = $level_array = array();
		while (!empty($arr))
		{
			foreach ($arr AS $key => $value)
			{
				$cat_id = $value['cat_id'];
				if ($level == 0 && $last_cat_id == 0)
				{
					if ($value['parent_id'] > 0)
					{
						break;
					}

					$options[$cat_id]          = $value;
					$options[$cat_id]['level'] = $level;
					$options[$cat_id]['id']    = $cat_id;
					$options[$cat_id]['name']  = $value['cat_name'];
					unset($arr[$key]);

					if ($value['has_children'] == 0)
					{
						continue;
					}
					$last_cat_id  = $cat_id;
					$cat_id_array = array($cat_id);
					$level_array[$last_cat_id] = ++$level;
					continue;
				}

				if ($value['parent_id'] == $last_cat_id)
				{
					$options[$cat_id]          = $value;
					$options[$cat_id]['level'] = $level;
					$options[$cat_id]['id']    = $cat_id;
					$options[$cat_id]['name']  = $value['cat_name'];
					unset($arr[$key]);

					if ($value['has_children'] > 0)
					{
						if (end($cat_id_array) != $last_cat_id)
						{
							$cat_id_array[] = $last_cat_id;
						}
						$last_cat_id    = $cat_id;
						$cat_id_array[] = $cat_id;
						$level_array[$last_cat_id] = ++$level;
					}
				}
				elseif ($value['parent_id'] > $last_cat_id)
				{
					break;
				}
			}

			$count = count($cat_id_array);
			if ($count > 1)
			{
				$last_cat_id = array_pop($cat_id_array);
			}
			elseif ($count == 1)
			{
				if ($last_cat_id != end($cat_id_array))
				{
					$last_cat_id = end($cat_id_array);
				}
				else
				{
					$level = 0;
					$last_cat_id = 0;
					$cat_id_array = array();
					continue;
				}
			}

			if ($last_cat_id && isset($level_array[$last_cat_id]))
			{
				$level = $level_array[$last_cat_id];
			}
			else
			{
				$level = 0;
			}
		}
		$cat_options[0] = $options;
	}
	else
	{
		$options = $cat_options[0];
	}

	if (!$spec_cat_id)
	{
		return $options;
	}
	else
	{
		if (empty($options[$spec_cat_id]))
		{
			return array();
		}

		$spec_cat_id_level = $options[$spec_cat_id]['level'];

		foreach ($options AS $key => $value)
		{
			if ($key != $spec_cat_id)
			{
				unset($options[$key]);
			}
			else
			{
				break;
			}
		}

		$spec_cat_id_array = array();
		foreach ($options AS $key => $value)
		{
			if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
			($spec_cat_id_level > $value['level']))
			{
				break;
			}
			else
			{
				$spec_cat_id_array[$key] = $value;
			}
		}
		$cat_options[$spec_cat_id] = $spec_cat_id_array;

		return $spec_cat_id_array;
	}
}


/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 *
 * @return   void
 */
function db_create_in($item_list, $field_name = '')
{
	if (empty($item_list))
	{
		return $field_name . " IN ('') ";
	}
	else
	{
		if (!is_array($item_list))
		{
			$item_list = explode(',', $item_list);
		}
		$item_list = array_unique($item_list);
		$item_list_tmp = '';
		foreach ($item_list AS $item)
		{
			if ($item !== '')
			{
				$item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
			}
		}
		if (empty($item_list_tmp))
		{
			return $field_name . " IN ('') ";
		}
		else
		{
			return $field_name . ' IN (' . $item_list_tmp . ') ';
		}
	}
}

/**
 * 获得指定文章分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 *
 * @return void
 */
function get_article_children ($cat = 0)
{
	return db_create_in(array_unique(array_merge(array($cat), array_keys(article_cat_list($cat, 0, false)))), 'cat_id');
}

/**
 * 获得指定分类下的子分类的数组
 *
 * @access  public
 * @param   int     $cat_id     分类的ID
 * @param   int     $selected   当前选中分类的ID
 * @param   boolean $re_type    返回的类型: 值为真时返回下拉列表,否则返回数组
 * @param   int     $level      限定返回的级数。为0时返回所有级数
 * @param   int     $is_show_all 如果为true显示所有分类，如果为false隐藏不可见分类。
 * @return  mix
 */
function cat_list($cat_id = 0, $selected = 0, $re_type = true, $level = 0, $is_show_all = true)
{
	static $res = NULL;

	if ($res === NULL)
	{
		$data = read_static_cache('cat_pid_releate');
		if ($data === false)
		{
			$sql = "SELECT c.cat_id, c.cat_name, c.measure_unit, c.parent_id, c.is_show, c.show_in_nav, c.grade, c.sort_order, COUNT(s.cat_id) AS has_children ".
                'FROM ' . TABLEPRE . "category AS c ".
                "LEFT JOIN " . TABLEPRE . "category AS s ON s.parent_id=c.cat_id ".
                "GROUP BY c.cat_id ".
                'ORDER BY c.parent_id, c.sort_order ASC';
			$res = $GLOBALS['db']->getAll($sql);


			$newres = array();
			foreach((array)$res2 as $k=>$v)
			{
				$newres[$v['cat_id']] = $v['goods_num'];
				foreach($res3 as $ks=>$vs)
				{
					if($v['cat_id'] == $vs['cat_id'])
					{
						$newres[$v['cat_id']] = $v['goods_num'] + $vs['goods_num'];
					}
				}
			}

			foreach($res as $k=>$v)
			{
				$res[$k]['goods_num'] = !empty($newres[$v['cat_id']]) ? $newres[$v['cat_id']] : 0;
			}
			//如果数组过大，不采用静态缓存方式
			if (count($res) <= 1000)
			{
				write_static_cache('cat_pid_releate', $res);
			}
		}
		else
		{
			$res = $data;
		}
	}

	if (empty($res) == true)
	{
		return $re_type ? '' : array();
	}

	$options = cat_options($cat_id, $res); // 获得指定分类下的子分类的数组

	$children_level = 99999; //大于这个分类的将被删除
	if ($is_show_all == false)
	{
		foreach ($options as $key => $val)
		{
			if ($val['level'] > $children_level)
			{
				unset($options[$key]);
			}
			else
			{
				if ($val['is_show'] == 0)
				{
					unset($options[$key]);
					if ($children_level > $val['level'])
					{
						$children_level = $val['level']; //标记一下，这样子分类也能删除
					}
				}
				else
				{
					$children_level = 99999; //恢复初始值
				}
			}
		}
	}

	/* 截取到指定的缩减级别 */
	if ($level > 0)
	{
		if ($cat_id == 0)
		{
			$end_level = $level;
		}
		else
		{
			$first_item = reset($options); // 获取第一个元素
			$end_level  = $first_item['level'] + $level;
		}

		/* 保留level小于end_level的部分 */
		foreach ($options AS $key => $val)
		{
			if ($val['level'] >= $end_level)
			{
				unset($options[$key]);
			}
		}
	}

	if ($re_type == true)
	{
		$select = '';
		foreach ($options AS $var)
		{
			$select .= '<option value="' . $var['cat_id'] . '" ';
			$select .= ($selected == $var['cat_id']) ? "selected='ture'" : '';
			$select .= '>';
			if ($var['level'] > 0)
			{
				$select .= str_repeat('&nbsp;', $var['level'] * 4);
			}
			$select .= htmlspecialchars(addslashes($var['cat_name']), ENT_QUOTES) . '</option>';
		}

		return $select;
	}
	else
	{
		foreach ($options AS $key => $value)
		{
			$options[$key]['url'] = build_uri('category', array('cid' => $value['cat_id']), $value['cat_name']);
		}

		return $options;
	}
}

/**
 * 过滤和排序所有分类，返回一个带有缩进级别的数组
 *
 * @access  private
 * @param   int     $cat_id     上级分类ID
 * @param   array   $arr        含有所有分类的数组
 * @param   int     $level      级别
 * @return  void
 */
function cat_options($spec_cat_id, $arr)
{
	static $cat_options = array();

	if (isset($cat_options[$spec_cat_id]))
	{
		return $cat_options[$spec_cat_id];
	}

	if (!isset($cat_options[0]))
	{
		$level = $last_cat_id = 0;
		$options = $cat_id_array = $level_array = array();
		$data = read_static_cache('cat_option_static');
		if ($data === false)
		{
			while (!empty($arr))
			{
				foreach ($arr AS $key => $value)
				{
					$cat_id = $value['cat_id'];
					if ($level == 0 && $last_cat_id == 0)
					{
						if ($value['parent_id'] > 0)
						{
							break;
						}

						$options[$cat_id]          = $value;
						$options[$cat_id]['level'] = $level;
						$options[$cat_id]['id']    = $cat_id;
						$options[$cat_id]['name']  = $value['cat_name'];
						unset($arr[$key]);

						if ($value['has_children'] == 0)
						{
							continue;
						}
						$last_cat_id  = $cat_id;
						$cat_id_array = array($cat_id);
						$level_array[$last_cat_id] = ++$level;
						continue;
					}

					if ($value['parent_id'] == $last_cat_id)
					{
						$options[$cat_id]          = $value;
						$options[$cat_id]['level'] = $level;
						$options[$cat_id]['id']    = $cat_id;
						$options[$cat_id]['name']  = $value['cat_name'];
						unset($arr[$key]);

						if ($value['has_children'] > 0)
						{
							if (end($cat_id_array) != $last_cat_id)
							{
								$cat_id_array[] = $last_cat_id;
							}
							$last_cat_id    = $cat_id;
							$cat_id_array[] = $cat_id;
							$level_array[$last_cat_id] = ++$level;
						}
					}
					elseif ($value['parent_id'] > $last_cat_id)
					{
						break;
					}
				}

				$count = count($cat_id_array);
				if ($count > 1)
				{
					$last_cat_id = array_pop($cat_id_array);
				}
				elseif ($count == 1)
				{
					if ($last_cat_id != end($cat_id_array))
					{
						$last_cat_id = end($cat_id_array);
					}
					else
					{
						$level = 0;
						$last_cat_id = 0;
						$cat_id_array = array();
						continue;
					}
				}

				if ($last_cat_id && isset($level_array[$last_cat_id]))
				{
					$level = $level_array[$last_cat_id];
				}
				else
				{
					$level = 0;
				}
			}
			//如果数组过大，不采用静态缓存方式
			if (count($options) <= 2000)
			{
				write_static_cache('cat_option_static', $options);
			}
		}
		else
		{
			$options = $data;
		}
		$cat_options[0] = $options;
	}
	else
	{
		$options = $cat_options[0];
	}

	if (!$spec_cat_id)
	{
		return $options;
	}
	else
	{
		if (empty($options[$spec_cat_id]))
		{
			return array();
		}

		$spec_cat_id_level = $options[$spec_cat_id]['level'];

		foreach ($options AS $key => $value)
		{
			if ($key != $spec_cat_id)
			{
				unset($options[$key]);
			}
			else
			{
				break;
			}
		}

		$spec_cat_id_array = array();
		foreach ($options AS $key => $value)
		{
			if (($spec_cat_id_level == $value['level'] && $value['cat_id'] != $spec_cat_id) ||
			($spec_cat_id_level > $value['level']))
			{
				break;
			}
			else
			{
				$spec_cat_id_array[$key] = $value;
			}
		}
		$cat_options[$spec_cat_id] = $spec_cat_id_array;

		return $spec_cat_id_array;
	}
}

function get_wh_arr()
{
	return array('VIP_NH'=>'广州仓','VIP_SH'=>'上海仓','VIP_CD'=>'成都仓','VIP_BJ'=>'北京仓');
}
/**
 * 输出json信息
 * @param mixed $result 要输出的信息
 * @return void
 */
function outputJson($result,$is_die = true)
{
	static $json = NULL;
	if($json === NULL)
	{
		include_once(ROOT_PATH . 'includes/cls_json.php');
		$json = new Json();
	}

	if($is_die)
	die($json->encode($result));
	else
	return $json->encode($result);
}